<?php

namespace app\common\exception;


use app\common\traits\InstanceTrait;
use Helper\ResponseHelper;
use think\Exception;


/**
 * Class BaseException
 * 自定义异常类的基类
 */
class BaseException extends Exception
{
    use InstanceTrait;

    protected $info = [
        'code' => 0,
        'msg' => '',
        'data' => [],
    ];

    /**
     * 构造函数，设置异常的信息(用于自定义)
     * @param array $params 关联数组应包含code、msg和data，且不应该是空值
     */
    public function __construct($params = [], $msg = '', $data = [])
    {
        parent::__construct();
        $this->setInfo($params, $msg, $data);
    }


    /**
     * 获取异常返回信息 code,msg,data
     * @return array
     */
    public function getInfo()
    {
        $ret = ResponseHelper::getResponseExample();
        $ret = array_merge($ret, $this->info);
        return $ret;
    }


    /**
     * 设置异常信息并抛出
     * @param array $exception_config
     * @throws BaseException
     */
    public static function throwException(array $exception_config, $msg = '', $data = '')
    {
        $exception = static::instance();
        $exception->setInfo($exception_config, $msg, $data);

        throw $exception;
    }

    /**
     * 设置异常的信息(用于自定义)
     * @param array $params 关联数组 key可以为code,msg,data
     * @param string $msg
     * @param array $data
     * @return $this
     */
    protected function setInfo($params = [], $msg = '', $data = [])
    {
        if (!empty($params)) {
            if (!empty($params['code'])) {
                $this->info['code'] = $params['code'];
            }
            if (!empty($params['msg'])) {
                $this->info['msg'] = $params['msg'];
            }
            if (!empty($params['data'])) {
                $this->info['data'] = array_merge($this->info['code'], $params['data']);
            }
        }

        if (!empty($msg)) {
            $this->info['msg'] = $msg;
        }
        if (!empty($data)) {
            $this->info['data'] = $data;
        }
        return $this;
    }
}


